package com.vcit.clazz.controller;

import com.vcit.system.domain.course.TCourse;
import com.vcit.system.domain.grade.TClazzTermCourse;
import com.vcit.system.service.grade.ITClazzTermCourseService;
import com.vcit.system.service.course.ITCourseService;
import com.vcit.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import java.util.*;

/**
 * 学期、班级、课程 Controller
 *
 * @author dff
 * @date 2025-06-08
 */
@Api("学期、班级、课程管理")
@RestController
@RequestMapping("/clazzTermCourse")
public class TClazzTermCourseController {
    @Autowired
    private ITClazzTermCourseService service;
    @Autowired
    private ITCourseService courseService;

    /**
     * 查询三元关系详情（带学期、班级、课程名称）
     * 权限点：clazzTermCourse:view
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:view')")
    @GetMapping("/{id}")
    @ApiOperation("获取学期，班级，课程，关系")
    public TClazzTermCourse getById(@PathVariable Long id) {
        return service.selectByIdWithNames(id);
    }

    /**
     * 查询三元关系列表（带学期、班级、课程名称）
     * 权限点：clazzTermCourse:view
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:view')")
    @GetMapping("/list")
    @ApiOperation("获取学期，班级，课程，关系列表")
    public List<TClazzTermCourse> list(TClazzTermCourse query) {
        return service.selectListWithNames(query);
    }

    /**
     * 新增单条分配
     * 权限点：clazzTermCourse:add
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:add')")
    @PostMapping
    @ApiOperation("单条分配学期，班级，课程，关系")
    public int add(@RequestBody TClazzTermCourse entity) {
        return service.insert(entity);
    }

    /**
     * 批量分配
     * 权限点：clazzTermCourse:batchAdd
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:add')")
    @PostMapping("/batch")
    @ApiOperation("批量分配学期，班级，课程，关系（先删后增）")
    public AjaxResult batchAdd(@RequestBody List<TClazzTermCourse> list) {
        return AjaxResult.success(service.batchReplaceClazzTermCourses(list));
    }

    /**
     * 更新分配
     * 权限点：clazzTermCourse:edit
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:edit')")
    @PutMapping
    @ApiOperation("更新分配学期，班级，课程，关系")
    public int update(@RequestBody TClazzTermCourse entity) {
        return service.update(entity);
    }

    /**
     * 批量更新分配
     * 权限点：clazzTermCourse:edit
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:edit')")
    @PutMapping("/batch")
    @ApiOperation("批量更新学期，班级，课程，关系")
    public int batchUpdate(@RequestBody List<TClazzTermCourse> list) {
        return service.batchUpdate(list);
    }

    /**
     * 删除单条分配
     * 权限点：clazzTermCourse:remove
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:remove')")
    @DeleteMapping("/{id}")
    @ApiOperation("单条删除学期，班级，课程，关系")
    public int delete(@PathVariable Long id) {
        return service.deleteById(id);
    }

    /**
     * 批量删除分配
     * 权限点：clazzTermCourse:batchRemove
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:remove')")
    @DeleteMapping("/batch")
    @ApiOperation("批量删除学期，班级，课程，关系")
    public int deleteBatch(@RequestBody Long[] ids) {
        return service.deleteByIds(ids);
    }

    /**
     * 获取可选课程列表（未分配给该班级学期的课程，支持课程名模糊搜索）
     * 权限点：clazzTermCourse:view
     * @param clazzId 班级ID
     * @param termId 学期ID
     * @param courseName 课程名（可选，模糊搜索）
     * @return { total: 总数, list: 课程列表 }
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:view')")
    @GetMapping("/availableCourses")
    @ApiOperation("获取班级未分配课程列表")
    public Map<String, Object> getAvailableCourses(
            @RequestParam Long clazzId,
            @RequestParam Long termId,
            @RequestParam(required = false) String courseName) {
        // 查询所有课程（可带模糊搜索）
        TCourse courseQuery = new TCourse();
        if (courseName != null && !courseName.trim().isEmpty()) {
            courseQuery.setCourseName(courseName.trim());
        }
        List<TCourse> allCourses = courseService.selectTCourseList(courseQuery);
        // 查询该班级学期已分配的课程ID
        TClazzTermCourse query = new TClazzTermCourse();
        query.setClazzId(clazzId);
        query.setTermId(termId);
        List<TClazzTermCourse> assigned = service.selectList(query);
        Set<Long> assignedIds = new HashSet<>();
        // 数组转集合

        for (TClazzTermCourse c : assigned) assignedIds.add(c.getCourseId());
        // 过滤未分配的课程
        List<TCourse> result = new ArrayList<>();
        for (TCourse c : allCourses) {
            if (!assignedIds.contains(c.getId())) result.add(c);
        }
        Map<String, Object> resp =new HashMap<>();
        resp.put("total", result.size());
        resp.put("list", result);
        return resp;
    }

    /**
     * 获取班级某学期已经分配的课程列表（用于回显）
     * 权限点：clazzTermCourse:view
     * @param clazzId 班级ID
     * @param termId 学期ID
     * @return { total: 总数, list: 已分配课程列表（包含排序信息） }
     */
    @PreAuthorize("@ss.hasPermi('clazzTermCourse:view')")
    @GetMapping("/assignedCourses")
    @ApiOperation("获取班级已分配课程列表（回显用）")
    public Map<String, Object> getAssignedCourses(
            @RequestParam Long clazzId,
            @RequestParam Long termId) {
        // 查询该班级学期已分配的课程（带名称信息）
        TClazzTermCourse query = new TClazzTermCourse();
        query.setClazzId(clazzId);
        query.setTermId(termId);
        List<TClazzTermCourse> assignedCourses = service.selectListWithNames(query);
        
        Map<String, Object> resp = new HashMap<>();
        resp.put("total", assignedCourses.size());
        resp.put("list", assignedCourses);
        return resp;
    }
} 